import {
	getCookie,
	deleteCookie,
	setCookie
} from "@/utils/js-cookie.js"

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);

export const getToken = function() {
	const url = window.location.href;
	const match = url.match(/ECWEB-JWTSSO-TOKEN=([^&]+)/);
	let token = "";
	// 接口联调时，可以注释掉16-22行，打开23行写死token
	// let _token = urlParams.get("ECWEB-JWTSSO-TOKEN");
	let _token = Array.isArray(match) ? decodeURIComponent(match[1]) : '';
	if (_token) {
		token = _token;
	}
	if (!token) {
		token = window.localStorage.token;
	}
	token ='eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJwZXJzb25OYW1lIjoi5YiY5oyv5LitIiwicGVyc29uSWQiOiIzNDcwMmNjZTBiNjI0YWQ1OGI2YzkxMzAwMmM2MjE3MyIsInBlcnNvbkFjY291bnQiOiIxOTg3MzEyMDAzMSIsInBlcnNvbk1haWwiOiIxMjNAcXEuY29tIiwicGVyc29uTW9iaWxlIjoiMTk4NzMxMjAwMzEiLCJwZXJzb25Xb3JrVGVsIjpudWxsLCJwZXJzb25Db2RlIjpudWxsLCJwZXJzb25TZXR1cElkIjoiMzRhMjNkNmRiNjQ5NDIyN2ExMWExOTExZWFkODdlMWQiLCJwaG90b05hbWUiOiJJTUdfMjAyNDA4MDFfMTcwNTI4LmpwZyIsInBob3RvVXBkYXRlVGltZSI6MTcyMjUwMzA3MDAwMCwic3lzQ29kZSI6ImVjeW9hIiwic3lzTmFtZSI6IuaUv-azlemAmuW5s-WPsCIsIm9yZ0NvZGUiOiJwbGF0Iiwib3JnTmFtZSI6IuS4reWFsea5luWNl-ecgeWnlOaUv-azleWnlCIsInVpU3R5bGUiOiJza2luQmx1ZSIsImxlZnRNZW51TWluIjowLCJ0b2RvSGludCI6bnVsbCwicHdkRXhwaXJlVGltZSI6bnVsbCwiaDVpbmRleFVybCI6bnVsbCwib3BlbmZpcmVTZXJ2ZXIiOm51bGwsIm9wZW5maXJlWG1wcERvbWFpbiI6bnVsbCwiaW1laSI6bnVsbCwic3RhZmZMaXN0IjpudWxsLCJ1c2VySWQiOiIzNDcwMmNjZTBiNjI0YWQ1OGI2YzkxMzAwMmM2MjE3MyIsIm5pY2tOYW1lIjoi5YiY5oyv5LitIiwiZGVwdElkIjoiODE0MTAzNTBiZDAxNDNiZjhhZDhhY2I3YzBkNTQ3YmYiLCJkZXB0TmFtZSI6Iuecgee7vOayu-S4reW_gyIsInRva2VuIjpudWxsLCJsb2dpblRpbWUiOm51bGwsImV4cGlyZVRpbWUiOm51bGwsImlwYWRkciI6bnVsbCwibG9naW5Mb2NhdGlvbiI6bnVsbCwiYnJvd3NlciI6bnVsbCwib3MiOm51bGwsInBlcm1pc3Npb25zIjpudWxsLCJ1c2VyIjpudWxsLCJhY2NvdW50Tm9uRXhwaXJlZCI6dHJ1ZSwiand0VG9rZW5LZXkiOiJzZXNzaW9uOnBsYXQ6MTk4NzMxMjAwMzEiLCJhY2NvdW50Tm9uTG9ja2VkIjp0cnVlfQ.FtLtRHWA36NUt9Xu-1CaZiIx0-b3RXeHATBVv1oomWkNVTybEhS5dWHHT7gIPc2tmGMDrHkn1YzIIadATOG1E0ptr_riuh-5WgbPhARF8eF1iOlXUkOR8xTfvYA-3wzvNxkqVPYy2nWGYk3GY5ddaxDVP5DX4BeXXQvMIfafuew'
	uni.setStorageSync("token", token);
	return token;
};

// 数据提交三种不同的格式
const contentType = {
	json: "application/json;charset=UTF-8",
	form_urlencoded: "application/x-www-form-urlencoded;charset=UTF-8",
	form_data: "multipart/form-data;charset=UTF-8",
};

//根据环境获取baseUrl
export function getRequestUrl() {
	let baseUrl = " /zfw-app"
	if (process.env.NODE_ENV === 'development') {
		baseUrl = "/api"
	}
	return baseUrl
}

const request = ({
	url,
	method,
	data = {},
	isJson = false,
	isFormData = false,
	timeout = 50000,
	isLoading = true,
}) => {
	return new Promise((resolve, reject) => {
		if (isLoading) {
			uni.showLoading({
				title: "加载中...",
				mask: true,
			});
		}
		const requestUrl = getRequestUrl() + url;
		uni.request({
			url: requestUrl,
			method: method,
			data: data,
			header: {
				"Content-Type": isJson ?
					contentType.json : isFormData ?
					contentType.form_data : contentType.form_urlencoded,
				"ECWEB-JWTSSO-TOKEN": getToken(),
			},
			timeout,
			enableCache: true, // 自动处理缓存
			success: (res) => {
				if (isLoading) {
					uni.hideLoading();
				}
				try {
					if (res.statusCode === 200) {
						if (res.data.code == 200) {
							resolve(res.data);
						} else {
							uni.showToast({
								title: res.data.code == 500 && res.data.msg ?
									res.data.msg : "未知错误",
								icon: "none",
								duration: 1500,
							});
						}
					} else {
						resolve({
							code: "failure",
							message: "系统繁忙！",
						});
					}
				} catch (e) {
					resolve({
						code: "failure",
						message: "系统繁忙！",
					});
				}
			},
			fail: (err) => {
				if (isLoading) {
					uni.hideLoading();
				}
				reject("系统错误!" + err);
			},
		});
	});
};


//封装请求
export function asyncRequest(option) {
	return new Promise((resolve, reject) => {
		uni.request({
			header: {
				// 'ECWEB-JWTSSO-TOKEN':  option.url.indexOf('ecweb') == -1 ?  'Bearer ' + getToken() : getToken(),
				'ECWEB-JWTSSO-TOKEN':  'Bearer ' + getToken() ,
			},
			url: option.url.indexOf('ecweb') == -1 ? getRequestUrl() + option.url : option.url ,
			method: option.method,
			data: option.data,
			success: res => {
				if (res.data.code == 200 || res.data.code == 'success' || option.release) {
					resolve(res)
				}
				if (res.data.code == 400) {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 2000
					})
				}
				if (res.data.code == 401) {
					uni.reLaunch({
						url: '/pages/login/index'
					});
				}
				if (res.data.code == 500) { //发包
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					})
					reject(res)
				}
			},
			fail: error => {
				uni.hideLoading()
				uni.showToast({
					title: '加载失败，请重试！',
					icon: 'none'
				})
				reject(error)
			}
		})
	})
}

//封装请求
export function thirdRequest(option) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: getRequestUrl() + option.url,
			method: option.method,
			data: option.data,
			success: res => {
				if (res.data.infocode == 10000 || option.release) {
					resolve(res)
				} else {
					uni.showToast({
						title: res.data.msg,
						icon: 'none',
						duration: 2000
					})
					reject(res)
				}
			},
			fail: error => {
				uni.hideLoading()
				uni.showToast({
					title: '加载失败，请重试！',
					icon: 'none'
				})
				reject(error)
			}
		})
	})
}

//封装请求
export function uploadRequest(option) {
	const token = getCookie('Admin-Token')
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: getRequestUrl() + option.url, //仅为示例，非真实的接口地址
			formData: {
				'file': option.data
			},
			header: {
				'ECWEB-JWTSSO-TOKEN': 'Bearer ' + getToken(),
			},
			success: (res) => {
				const data = JSON.parse(res.data)
				resolve(data)
			},
			fail: (error) => {
				uni.showToast({
					title: '加载失败，请重试！',
					icon: 'none'
				})
				reject(error)
			}
		});
	})
}

export default request;